#include "pusher/mjpeg_stream_server.hpp"
#include "utils/log.hpp"

#include <string>
#include <iostream>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <signal.h>
#include <sys/socket.h>
#include <unistd.h>
#include <sstream>

void MJPEGStreamServer::HandleClient(int client_fd)
{
    LOG_DEBUG("[HandleClient] 处理 fd = ");

    struct timeval timeout = {5, 0};
    setsockopt(client_fd, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout));

    const std::string header =
    "HTTP/1.0 200 OK\r\n"
    "Content-Type: multipart/x-mixed-replace; boundary=frame\r\n\r\n";
    send(client_fd, header.c_str(), header.size(), 0);

    while (IsRunning()) {
        std::vector<uint8_t> frame;
        // 从 buffer 中获取图像帧
        if (!_buffer || !_buffer->GetFrame(frame)) {
            std::this_thread::sleep_for(std::chrono::milliseconds(10));
            continue;
        }

        std::ostringstream oss;
        oss << "--frame\r\n"
            << "Content-Type: image/jpeg\r\n"
            << "Content-Length: " << frame.size() << "\r\n\r\n";
        std::string frameHeader = oss.str();

        ssize_t h1 = send(client_fd, frameHeader.c_str(), frameHeader.size(), 0);
        ssize_t h2 = send(client_fd, frame.data(), frame.size(), 0);
        ssize_t h3 = send(client_fd, "\r\n", 2, 0);

        LOG_DEBUG("[HTTP] 发送帧：{}字节 (header={}, body={}, end={})", frame.size(), h1, h2, h3);


        std::this_thread::sleep_for(std::chrono::milliseconds(33));  // ~30fps
    }

    close(client_fd);
    LOG_DEBUG("[HandleClient] 关闭客户端处理 fd = ");
}

















